<?php

defined('MYLITS') ? '' : exit('No direct script access allowed');

/**
 * @version     1.0.0
 * @package     mylits engine
 * @license     GNU General Public License version 3
 * @author      Arfan Fudyartanto D N <arfan@mylits.com> - http://engine.mylits.com
 */
class Mylits_Security {

    private static $instance;

    private function __construct() {
        
    }

    /**
     * This method will return Mylits_Security object
     * 
     * @return object Mylits_Security
     */
    public static function getInstance() {
        if (is_null(self::$instance)) {
            self::$instance = new self();
        }
        return self::$instance;
    }

    /**
     * Method to encrypt with asymmetric encryption way, encrypted data can be decrypted
     * 
     * @param string $data
     * @param string $key
     * @return string encrypted data
     */
    public static function asymmetricEncrypt($data, $key = NULL) {
        if (empty($key)) {
            $key = Mylits_Config::getValue('encryption_key');
        }
        $result = md5(self::encrypt($data . $key)) . ":" . md5($key);
        return $result;
    }

    public static function encrypt($data, $key = NULL) {
        if (empty($key)) {
            $key = Mylits_Config::getValue('encryption_key');
        }
        #$data = base_convert($data, 10, 36); // Save some space
        $data = mcrypt_encrypt(MCRYPT_BLOWFISH, $key, $data, 'ecb');
        $data = bin2hex($data);

        return $data;
    }

    public static function decrypt($data, $key = NULL) {
        if (empty($key)) {
            $key = Mylits_Config::getValue('encryption_key');
        }
        $data = pack('H*', $data); // Translate back to binary
        $data = mcrypt_decrypt(MCRYPT_BLOWFISH, $key, $data, 'ecb');
        #$data = base_convert($data, 36, 10);

        return $data;
    }

}

?>
